from pyecharts.charts import Map
from pyecharts.options import LegendOpts, ToolboxOpts, VisualMapOpts, ToolBoxFeatureOpts, ToolBoxFeatureSaveAsImageOpts, \
    TitleOpts
import json
import requests
import re
import datetime


def get_data():
    # 获取数据
    url = 'https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner'
    response = requests.get(url)
    data_html = response.content.decode()
    json_str = re.findall('"component":\[(.*)\],', data_html)[0]  # 获取到component关键字后面的一个元素
    json_dict = json.loads(json_str)
    caseList = json_dict['caseList']
    Province_name_confirmedRelative = []
    Province_name_confirmed = []
    Province_name_crued = []
    for case in caseList:
        Province_name = case['area']  # 省份信息
        Province_confirmedRelative = case['confirmedRelative']  # 新增确诊人数
        Province_confirmed = case['confirmed']  # 累计确诊人数
        Province_crued = case['crued']  # 累计治愈人数
        print(Province_name, Province_confirmedRelative, Province_confirmed, Province_crued)
        Province_name_confirmedRelative.append((Province_name, Province_confirmedRelative))
        Province_name_confirmed.append((Province_name, Province_confirmed))
        Province_name_crued.append((Province_name, Province_crued))
    return Province_name_confirmedRelative, Province_name_confirmed, Province_name_crued


def visualization_data(data, title):
    map = Map()
    yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    map.add('{} {}'.format(yesterday, title), data, 'china')
    # 设置全局配置，定制分段的视觉映射
    map.set_global_opts(
        title_opts=TitleOpts(title=title, pos_bottom='1%', pos_left='center'),
        toolbox_opts=ToolboxOpts(is_show=True, feature=ToolBoxFeatureOpts(
            save_as_image=ToolBoxFeatureSaveAsImageOpts(type_='jpg', background_color='white'))),
        legend_opts=LegendOpts(is_show=True),
        visualmap_opts=VisualMapOpts(
            is_show=True,  # 是否显示
            is_piecewise=True,  # 是否分段显示
            pieces=[
                {'min': 1, 'max': 199, 'lable': '1-99人', 'color': "#FDEBD0"},
                {'min': 200, 'max': 399, 'lable': '100-999人', 'color': "#F39E86"},
                {'min': 400, 'max': 799, 'lable': '1000-4999人', 'color': "#E35B52"},
                {'min': 800, 'max': 999, 'lable': '5000-9999人', 'color': "#C92C34"},
                {'min': 1000, 'lable': '100000+', 'color': "#6F171F"}
            ]

        )
    )
    map.render("{}.html".format(title))


def main():
    Province_name_confirmedRelative, Province_name_confirmed, Province_name_crued = get_data()
    visualization_data(Province_name_confirmedRelative, "昨日确诊")
    visualization_data(Province_name_confirmed, "累计确诊")
    visualization_data(Province_name_crued, "累计治愈")


if __name__ == '__main__':
    main()
